import os  
import chardet  
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout,QHBoxLayout, QPushButton, QTextEdit, QFileDialog  
from PySide6.QtCore import Qt  
  
class TextFileConverter(QWidget):  
    def __init__(self):  
        super().__init__()  
        self.initUI()  
  
    def initUI(self):  
        self.setWindowTitle('文本文件编码转换')  
        self.setGeometry(300, 200, 800, 600)  
        layout = QVBoxLayout(self)  
  
        self.folderPath = ""  
        self.resultText = QTextEdit(self)  
        self.resultText.setReadOnly(True)
        self.textLayout = QHBoxLayout(self)  
        self.textLayout.addWidget(self.resultText)
            
        layout.addLayout(self.textLayout)  
  
        self.selectFolderButton = QPushButton('选择文件夹', self)  
        self.selectFolderButton.clicked.connect(self.selectFolder)  
        layout.addWidget(self.selectFolderButton)  
  
        self.convertButton = QPushButton('开始转换', self)  
        self.convertButton.clicked.connect(self.convertFiles)  
        self.convertButton.setEnabled(False)  
        layout.addWidget(self.convertButton)  
  
        self.setLayout(layout)  
  
    def selectFolder(self):  
        directory = QFileDialog.getExistingDirectory(self, "Please select a directory")  
        if directory:  
            self.folderPath = directory  
            self.convertButton.setEnabled(True)  
  
    def convertFiles(self):  
        self.resultText.clear()  
        if not self.folderPath:  
            self.resultText.append("Please select a folder first.")  
            return  
  
        folderPathLength = len(self.folderPath) + (1 if self.folderPath.endswith('/') or self.folderPath.endswith('\\') else 0)
        projectFolder = os.path.basename(self.folderPath)
        for root, dirs, files in os.walk(self.folderPath):  
            for file in files:  
                if file.lower().endswith(('.txt','.c','.h')):  # Add more extensions if needed  
                    filePath = os.path.join(root, file)  
                    relativePath = os.path.join(projectFolder, filePath[folderPathLength+1:])   # 获取相对路径
                    # Detect original encoding  
                    with open(filePath, 'rb') as f:  
                        raw_data = f.read()  
                        result = chardet.detect(raw_data)  
                        originalEncoding = result['encoding']  
  
                    # Convert to UTF-8  
                    try:  
                        with open(filePath, 'r', encoding=originalEncoding, errors='ignore') as f:  
                            content = f.read()  
  
                        with open(filePath, 'w', encoding='utf-8') as f:  
                            f.write(content)  
                        self.resultText.append(f"从 <span style='color: red;'>[{originalEncoding}]</span> 转到 [UTF-8] ====> 文件地址: {relativePath} ") 
                    except Exception as e:  
                        self.resultText.append(f"Error converting {relativePath}: {e}")  
  
if __name__ == '__main__':  
    app = QApplication([])  
    converter = TextFileConverter()  
    converter.show()  
    app.exec()